package org.wyf.EveryPoint.crowd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.wyf.EveryPoint.common.annotation.ControllerEndpoint;
import org.wyf.EveryPoint.common.constants.D;
import org.wyf.EveryPoint.common.controller.BaseController;
import org.wyf.EveryPoint.common.entity.DictItem;
import org.wyf.EveryPoint.common.entity.FebsConstant;
import org.wyf.EveryPoint.common.entity.FebsResponse;
import org.wyf.EveryPoint.common.entity.QueryRequest;
import org.wyf.EveryPoint.common.service.IDictItemService;
import org.wyf.EveryPoint.common.utils.FileUtil;
import org.wyf.EveryPoint.crowd.entity.CollectionProject;
import org.wyf.EveryPoint.crowd.entity.Project;
import org.wyf.EveryPoint.crowd.entity.Team;
import org.wyf.EveryPoint.crowd.service.ICollectionProjectService;
import org.wyf.EveryPoint.crowd.service.IProjectService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.wyf.EveryPoint.common.utils.FebsUtil;
import org.wyf.EveryPoint.crowd.service.ITeamService;
import org.wyf.EveryPoint.system.entity.User;
import org.wyf.EveryPoint.system.service.IDeptService;
import org.wyf.EveryPoint.system.service.IUserService;

/**
 * 项目表 Controller
 *
 * @author wyf
 * @date 2021-04-09 16:56:53
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class ProjectController extends BaseController {

    private final IProjectService projectService;
    private final IDictItemService dictItemService;
    @Value("${everypoint.file.material}")
    private String material;
    private final String ctx = "/";
    private final ITeamService teamService;
    private final IUserService userService;
    private final ICollectionProjectService collectionProjectService;
    private final IDeptService deptService;

    /**
     * 获取首页Banner  点击量前3的项目的banner
     *
     * @return
     */
    @ControllerEndpoint(operation = "获取Banner", exceptionMessage = "获取Banner失败")
    @PostMapping("/web/common/getBanner")
    @ResponseBody
    public FebsResponse getBanner() {
        List<Project> list = projectService.getBanner();
        return new FebsResponse().success().data(list);
    }

    /**
     * 获取首页展示  点击量前9的项目
     *
     * @return
     */
    @ControllerEndpoint(operation = "获取首页展示", exceptionMessage = "获取首页展示失败")
    @PostMapping("/web/common/getIndexShow")
    @ResponseBody
    public FebsResponse getIndexShow() {
        List<Project> projects = projectService.getIndexShow();
        if (getCurrentUser() != null) {
            CollectionProject collectionProject = new CollectionProject();
            collectionProject.setUid(getCurrentUser().getUserId());
            List<CollectionProject> collectionProjects = collectionProjectService.findCollectionProjects(collectionProject);
            for (int i = 0; i < projects.size(); i++) {
                Project project = projects.get(i);
                for (int j = 0; j < collectionProjects.size(); j++) {
                    if (project.getProjectId().equals(collectionProjects.get(j).getPid())) {
                        projects.get(i).setCollectionFlag(true);
                        break;
                    }
                }
                if (projects.get(i).getCollectionFlag() == null) {
                    projects.get(i).setCollectionFlag(false);
                }
            }

        }
        return new FebsResponse().success().data(projects);
    }

    /**
     * 获取项目类型下拉框
     *
     * @return
     */
    @ControllerEndpoint(operation = "获取项目类型下拉框", exceptionMessage = "获取项目类型下拉框失败")
    @GetMapping("/web/getProjectType")
    @ResponseBody
    public FebsResponse getProjectType() {
        List<DictItem> data = dictItemService.findDictItems(D.PROJECT_TYPE);
        return new FebsResponse().success().data(data);
    }

    /**
     * 获取项目类型下拉框加上统计后的总数
     *
     * @return
     */
    @ControllerEndpoint(operation = "获取项目类型下拉框", exceptionMessage = "获取项目类型下拉框失败")
    @GetMapping("/web/common/getProjectTypeAndCount")
    @ResponseBody
    public FebsResponse getProjectTypeAndCount() {
        List<DictItem> data = dictItemService.findDictItems(D.PROJECT_TYPE);
        List<Map> count = projectService.countProjectOfType();
        for (int i = 0; i < data.size(); i++) {
            DictItem dictItem = data.get(i);
            for (int j = 0; j < count.size(); j++) {
                Map map = count.get(j);
                if (dictItem.getCode().equals(map.get("type"))) {
                    data.get(i).setCount((Long) map.get("count"));
                    break;
                }
            }
            if (data.get(i).getCount() == null) {
//                data.get(i).setCount(0L);
                data.remove(i);
                i--; // remove 后下标前移
            }

        }
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("where state in (3,5,7)");
        int countNum = projectService.count(queryWrapper);
        Map map = new HashMap();
        map.put("data", data);
        map.put("countNum", countNum);
        return new FebsResponse().success().data(map);
    }

    /**
     * 创建一个新项目
     *
     * @param project
     * @return
     */
    @ControllerEndpoint(operation = "创建项目", exceptionMessage = "创建项目失败")
    @PostMapping("/web/creatProject")
    @ResponseBody
    public FebsResponse creatProject(Project project) {
        User user = getCurrentUser();
        project.setUid(user.getUserId());
        // 这儿是创建一个项目的基本信息
        // 标题 短标题  简介  类别   开始时间  结束时间 目标金额 ==> 表单信息
        // uid  发起人信息   状态 0 未提交
        project.setState(0);
        project.setSubmitCount(0);
        project.setCreateTime(new Date());
        projectService.save(project);
        return new FebsResponse().success().data(project.getProjectId());
    }

    /**
     * 更新信息
     *
     * @param project
     * @return
     */
    @ControllerEndpoint(operation = "更新项目基本信息", exceptionMessage = "更新项目基本信息失败")
    @PostMapping("/web/updateProjectBase")
    @ResponseBody
    public FebsResponse updateProjectBase(Project project) {
        projectService.updateProject(project);
        return new FebsResponse().success().data(project.getProjectId());
    }

    /**
     * 项目封面图 上传
     *
     * @return
     */
    @ControllerEndpoint(operation = "项目封面图上传", exceptionMessage = "项目封面图上传失败")
    @PostMapping("web/updateCover")
    @ResponseBody
    public FebsResponse updateCover(@RequestParam("file") MultipartFile cover) {
        String url = Project.COVER_IMG_URL;
        url += FileUtil.upFile(cover, material + url);
        return new FebsResponse().success().data(url);
    }

    /**
     * 首页广告图 上传
     *
     * @return
     */
    @ControllerEndpoint(operation = "首页广告图上传", exceptionMessage = "首页广告图上传失败")
    @PostMapping("web/updateAd")
    @ResponseBody
    public FebsResponse updateAd(@RequestParam("file") MultipartFile ad) {
        String url = Project.AD_IMG_URL;
        url += FileUtil.upFile(ad, material + url);
        return new FebsResponse().success().data(url);
    }

    /**
     * 推荐轮播图 上传
     *
     * @return
     */
    @ControllerEndpoint(operation = "推荐轮播图上传", exceptionMessage = "推荐轮播图上传失败")
    @PostMapping("web/updateBanner")
    @ResponseBody
    public FebsResponse updateBanner(@RequestParam("file") MultipartFile banner) {
        String url = Project.BANNER_IMG_URL;
        url += FileUtil.upFile(banner, material + url);
        return new FebsResponse().success().data(url);
    }

    /**
     * 详细图片 上传
     *
     * @return
     */
    @ControllerEndpoint(operation = "推荐轮播图上传", exceptionMessage = "推荐轮播图上传失败")
    @PostMapping("web/updateDetailImag")
    @ResponseBody
    public Map<String, Object> updateDetailImag(@RequestParam("file") MultipartFile detail) {
        String url = Project.DETAIL_IMG_URL;
        url += FileUtil.upFile(detail, material + url);
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "上传成功");
        Map data = new HashMap();
        data.put("src", ctx + url);
        data.put("title", ctx + url);
        map.put("data", data);

        return map;
    }

    /**
     * 提交审核
     *
     * @return
     */
    @ControllerEndpoint(operation = "提交审核", exceptionMessage = "提交审核失败")
    @PostMapping("/web/submitProject")
    @ResponseBody
    public FebsResponse submitProject(Long projectId) {
        Team team = new Team();
        team.setPid(projectId);
        List<Team> list = teamService.findTeams(team);
        User user = new User();
        // 提交以后  发起者以及团队成员都变成了创作者,可以登录后台了
        user.setIsCreate("1");
        for (int i = 0; i < list.size(); i++) {
            user.setUserId(list.get(i).getUid());
            userService.updateById(user);
        }
        // 项目状态更正为 未审核
        Project project = new Project();
        project.setState(1);
        project.setProjectId(projectId);
        projectService.updateById(project);

        return new FebsResponse().success();
    }

    /**
     * 获取项目列表
     *
     * @return
     */
    @ControllerEndpoint(operation = "获取项目列表", exceptionMessage = "获取项目列表失败")
    @GetMapping("/web/getProjectList")
    @ResponseBody
    public FebsResponse getProjectList(QueryRequest queryRequest, String keyWord, String sortType) {

        Map data = getDataTable(projectService.getProjectList(queryRequest, keyWord, sortType));
        return new FebsResponse().success().data(data);
    }


    @ControllerEndpoint(operation = "获取关注项目列表", exceptionMessage = "获取关注项目列表失败")
    @GetMapping("/web/user/getCollectionProjectList")
    @ResponseBody
    public FebsResponse getCollectionProjectList(QueryRequest queryRequest) {

        Map data = getDataTable(projectService.getCollectionProjectList(queryRequest, getCurrentUser().getUserId()));
        return new FebsResponse().success().data(data);
    }

    @ControllerEndpoint(operation = "获取用户项目列表", exceptionMessage = "获取用户项目列表失败")
    @PostMapping("/web/user/getUserAllproject")
    @ResponseBody
    public FebsResponse getUserAllproject() {
        List<Project> list = projectService.getUserAllprojectByUid(getCurrentUser().getUserId());
        return new FebsResponse().success().data(list);
    }

    @ControllerEndpoint(operation = "获取用户项目列表", exceptionMessage = "获取用户项目列表失败")
    @PostMapping("/web/project/getUserProjectByState")
    @ResponseBody
    public FebsResponse getUserProjectByState(Integer state) {
        List<Project> list = projectService.getUserProjectByState(getCurrentUser().getUserId(), state);
        return new FebsResponse().success().data(list);
    }

    @GetMapping("/project/list")
    @ResponseBody
    public FebsResponse projectList(Project project, QueryRequest request) {
        long userId = getCurrentUser().getUserId();
        long deptId = getCurrentUser().getDeptId();
        // 获取当前用户下的所有部门号
        List<Long> ids = deptService.findDeptChilds(deptId);
        return new FebsResponse().success()
                .data(getDataTable(projectService.findProjects(request, project,ids)));
    }

    /**
     * 审核项目
     * @param project
     * @return
     */
    @ControllerEndpoint(operation = "审核项目", exceptionMessage = "审核项目失败")
    @PostMapping("/examProject")
    @ResponseBody
    public FebsResponse examProject(Project project) {
        project.setRemark(project.getRemark()+" 审核人："+getCurrentUser().getRealName());
        projectService.updateProject(project);
        return new FebsResponse().success();
    }
}
